package com.wswy.wzcx.ui.weather

import android.app.Activity
import android.arch.lifecycle.Observer
import android.content.Intent
import android.content.res.Resources
import android.graphics.Color
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentPagerAdapter
import android.support.v4.content.ContextCompat
import android.support.v4.view.ViewPager
import android.text.format.DateFormat
import android.util.Log
import com.blankj.utilcode.util.AdaptScreenUtils
import com.che.libcommon.utils.ToastUtils
import com.che.libcommon.widget.viewpager.VerticalViewPager
import com.wswy.wzcx.BuildConfig
import com.wswy.wzcx.R
import com.wswy.wzcx.model.weather.LiveWeather
import com.wswy.wzcx.model.weather.WeatherData
import com.wswy.wzcx.module.base.CBaseActivity
import com.wswy.wzcx.module.weather.AmapWeatherManager
import com.wswy.wzcx.module.weather.WeatherUtils
import com.wswy.wzcx.statistics.StatisticsId
import com.wswy.wzcx.ui.Constants
import com.wswy.wzcx.ui.dialog.LoadingDialog
import com.wswy.wzcx.ui.main.home.INewsView
import com.wswy.wzcx.utils.ShareDialog
import com.wswy.wzcx.utils.ShareHelper
import com.wswy.wzcx.utils.UiUtils
import kotlinx.android.synthetic.main.activity_weather.*


class WeatherActivity : CBaseActivity() {

    private companion object {
        private const val TAG = "WeatherActivity"

        private const val REQ_TAKE_SCREEN = 2
    }

    private var currShareType = -1

    private var loadingDialog:LoadingDialog?=null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_weather)

        UiUtils.setStatusBarLight(this, false)

        UiUtils.injectSpaceStatusBarHeight(place_bar)

        AmapWeatherManager.reloadWeather()

        AmapWeatherManager.getWeatherLiveData().value?.run {

            if (completed()){
                show(this)
            }else{

                loadingDialog = LoadingDialog(this@WeatherActivity,"加载中...").apply {
                    startLoading("加载中...")
                }

                AmapWeatherManager.getWeatherLiveData().observe(this@WeatherActivity, Observer {
                    it?.run {

                        if (completed()){
                            loadingDialog?.dismiss()
                            show(this)
                        }

                    }
                })

            }

        }

        initView()

    }

    private fun initView(){
        img_back.setOnClickListener {
            finish()
        }

        img_refresh.setOnClickListener {
            //刷新
        }

        img_share.setOnClickListener {
            //分享

            sendClickEvent(StatisticsId.main_weather_share)

            ShareDialog(it.context){
                currShareType = it


                startActivityForResult(Intent(applicationContext,ProxyScreenActivity::class.java).apply {
                    putExtra(Constants.EXTRA_DATA,AmapWeatherManager.getWeatherLiveData().value)
                }, REQ_TAKE_SCREEN)

            }.show()
        }
    }

    private fun show(weatherData: WeatherData){

        weatherData.liveWeather?.run {

            tv_city.text = city
            tv_last_update_time.text = getString(R.string.weather_last_update, DateFormat.format("HH:mm",reportTime))



            root_content.setBackgroundResource(WeatherUtils.getWeatherBg(weather))
            img_fg.setImageURI(WeatherUtils.getWeatherFg(weather),null)
        }


        view_pager.offscreenPageLimit = 2

        var rCurrRv:INewsView?=null

        view_pager.setOutScroller(object : VerticalViewPager.OutScroller{
            override fun canScroll(): Boolean {
                return rCurrRv?.rvCanScroll()?:false
            }
        })

        view_pager.addOnPageChangeListener(object :ViewPager.SimpleOnPageChangeListener(){
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels)
                //Log.e(TAG, " --> $position    $positionOffset   $positionOffsetPixels");

                changeStatusBar(position == 1 && positionOffsetPixels == 0,weatherData.liveWeather)

            }

        })

        view_pager.adapter = object : FragmentPagerAdapter(supportFragmentManager){
            override fun getItem(position: Int): Fragment {
                return if (position == 0) WeatherFragment() else WeatherNewsFragment().apply {
                    this.currRv = {
                        rCurrRv = it
                        null
                    }
                }
            }

            override fun getCount(): Int  = 2

            override fun getPageTitle(position: Int): CharSequence? {
                return if (position == 0) "weather" else "news"
            }
        }


    }


    private var isScrollNewsTop = false

    private fun changeStatusBar(isNewsTop:Boolean,weather: LiveWeather?){
        if (isScrollNewsTop == isNewsTop){
            return
        }

        if (isNewsTop){



            //setTranslucentStatus()
            UiUtils.setStatusBarLight(this, true)
            //UiUtils.injectSpaceStatusBarHeight(place_bar,ViewGroup.LayoutParams.WRAP_CONTENT)
            root_content.setBackgroundColor(Color.TRANSPARENT)
            layout_title.setBackgroundColor(Color.WHITE)
            img_back.setImageResource(R.drawable.btn_back_selector)
            tv_city.setTextColor(ContextCompat.getColor(applicationContext,R.color.textColorPrimary))
            tv_last_update_time.setTextColor(ContextCompat.getColor(applicationContext,R.color.textColorPrimary_40))

            img_share.setColorFilter(ContextCompat.getColor(applicationContext,R.color.colorPrimary))
            img_refresh.setColorFilter(ContextCompat.getColor(applicationContext,R.color.colorPrimary))
        }else{
            //removeTranslucentStatus()
            UiUtils.setStatusBarLight(this, false)
            //UiUtils.injectSpaceStatusBarHeight(place_bar)
            root_content.setBackgroundResource(WeatherUtils.getWeatherBg(weather?.weather))
            layout_title.setBackgroundColor(Color.TRANSPARENT)
            img_back.setImageResource(R.drawable.btn_back_white_selector)
            tv_city.setTextColor(Color.WHITE)
            tv_last_update_time.setTextColor(ContextCompat.getColor(applicationContext,R.color.white50))
            img_share.setColorFilter(Color.WHITE)
            img_refresh.setColorFilter(Color.WHITE)
        }

        isScrollNewsTop = isNewsTop
    }


    override fun autoHackStatusBar(): Boolean {
        return false
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == REQ_TAKE_SCREEN && resultCode == Activity.RESULT_OK){

            data?.getStringExtra(Constants.EXTRA_DATA)?.let {

                // path
                if (BuildConfig.DEBUG){
                    Log.e(TAG, " -->path $it ")
                }

                if (currShareType >= 0){
                    if (ShareHelper.isWXAppInstalled()){
                        ShareHelper.sharePic(applicationContext,it,currShareType)
                    }else{
                        ToastUtils.showText("未安装微信")
                    }
                    
                }

            }
        }

    }

    override fun getResources(): Resources {
//        AdaptScreenUtils.
        return AdaptScreenUtils.adaptHeight(super.getResources(),1920)
    }

    override fun onDestroy() {
        super.onDestroy()
        loadingDialog?.dismiss()
        AmapWeatherManager.getWeatherLiveData().removeObservers(this)
    }

}